package com.czk.springcloud.config;

import com.czk.springcloud.entity.CommonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 对返回值进行封装判断
 *
 * @Author:ChenZhangKun
 * @Date: 2021/11/18 15:09
 */
@RestControllerAdvice(basePackages = "com.czk")
@Slf4j
public class BaseResponseAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // Feign请求时通过拦截器设置请求头，如果是Feign请求则直接返回实体对象
        boolean isFeign = serverHttpRequest.getHeaders().containsKey("czk");
        if (isFeign) {
            return o;
        }
        if (o instanceof String) {
            return objectMapper.writeValueAsString(new CommonResult(200, "成功", (String) o));
        }
        if (o instanceof CommonResult) {
            return o;
        }
        return new CommonResult<>(200, "成功", o);
    }
}
